const express = require('express');

require( '../models/association' );

const Topic = require( '../models/topic' );
const Customer = require( '../models/customer' );
const random = require( '../utils/random' );

const { Op } = require("sequelize");

const router = express.Router();

// 获取话题列表(支持分页)
router.get( '/topic/list' , (req,resp,next)=>{
    next();
}, async (req,resp)=>{
    // 获取请求参数
    let { pageSize , currentPage } = req.query ;
    // 将 string 转换为 number
    pageSize = pageSize * 1 ;
    currentPage = currentPage * 1 ;
    console.log( req.query );

    let start = ( currentPage - 1 ) * pageSize ;

    let { count , rows } = await Topic.findAndCountAll( {
        attributes: [ 'id' , 'title' , 'publishTime'],
        offset: start ,
        limit: pageSize ,
        include: {
            model: Customer,
            attributes: [ 'id' , 'username' , 'nickname' ]
        }
    });

    console.log( count );
    console.log( rows );

    let result = {
        total: count ,
        pageSize: pageSize,
        currentPage: currentPage,
        topics: rows
    }

    resp.json( result );
});

// 查询话题
router.get( '/topic/search' , (req,resp,next) => {
    next();
}, async (req,resp)=>{

    let { type , keyword , pageSize , currentPage } = req.query ;

    type = type ? type : 'title' ;

    // 将 string 转换为 number
    pageSize = +pageSize ;
    currentPage = +currentPage ;

    let start = ( currentPage - 1 ) * pageSize ;

    let { count , rows } = await Topic.findAndCountAll( {
        attributes: [ 'id' , 'title' , 'publishTime'],
        offset: start ,
        limit: pageSize ,
        include: {
            model: Customer,
            attributes: [ 'id' , 'username' , 'nickname' ]
        },
        where: {
            // 取 type 变量的值作 属性名 (即查询条件)
            [type]: {
                [Op.like] : `%${keyword}%`
            }
        }
    });

    let result = {
        total: count ,
        pageSize: pageSize,
        currentPage: currentPage,
        topics: rows
    }

    resp.json( result );

});

// 发布话题
router.post( '/topic/publish' , (req,resp,next)=>{
    // 在这里完成数据校验
    next();
},(req,resp)=>{
    //  由 jwtMiddleware 解析 JWT 后将 payload 设置到 req.user 中
    let customer = req.user ;
    if( customer ) {
        let { title , content } = req.body ;
        let topic = {
            id: random.id(),
            title,
            content,
            publishTime: new Date(),
            publishIp: req.ip ,
            cid: customer.id
        }

        Topic.create( topic )
             .then( result=>{
                 console.log( 'result: ' , result );
                 resp.json( { success: true , message: '发布成功' } );
             }).catch( error=>{
                 console.log( 'error: ' , error );
                 resp.json( { success: false , message: '发布失败' , error } );
             });

        return ;
    }
    resp.json( { success: false , message: '发布失败(登录超时或未登录)' } );
});

module.exports = router ;